package com.qingkai.onlineshop.presentation.detail

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.qingkai.onlineshop.app.Route
import com.qingkai.onlineshop.data.AppDatabase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *作者：created by 89270 on 2025/6/17 09:40
 *描述：
 */
class DetailViewModel(private val appDatabase: AppDatabase, private val param: Route.Detail) :
    ViewModel() {
    private val _mState = MutableStateFlow(DetailState())
    val state = _mState.onStart { initItem() }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _mState.value)

    private fun initItem() {
        viewModelScope.launch {
            val find = appDatabase.itemDao().getFullItemData().find { it.item.id == param.id }
            _mState.update { it.copy(itemFull = find) }
        }
    }

    fun increase() {
        _mState.update {
            val value = it.count + 1
            it.copy(count = value, total = (it.itemFull!!.item.price * value).toDouble())
        }
    }

    fun decrease() {
        _mState.update {
            val value = (it.count - 1).coerceAtLeast(0)
            it.copy(count = value, total = (it.itemFull!!.item.price * value).toDouble())
        }
    }
}